<template>
  <iframe
    title="人员选择"
    ref="userSelectIframe"
    style="
      overflow: hidden;
      width: 100%;
      height: 540px;
      border: thin none;
      outline: none;
      padding: 0;
      margin: 0;
      display: inline;
    "
    sandbox="allow-modals allow-forms allow-popups allow-scripts allow-top-navigation allow-same-origin"
    :src="selectConfig.userSelectIframeUrl"
  ></iframe>
</template>

<script lang="ts" setup>
const emit = defineEmits(["getSelectUserInfo"]);
const props = defineProps({
  selectType: {
    type: String,
    required: true,
    default: "p",
  },
  selectConfig: {
    type: Object,
    required: true,
    default: () => ({
      userSelectIframeUrl: "/", // 人员弹窗列表地址
      cookieDomain: "/", // cookie域
      postMessageTargetOrigin: "/", // postMessage接收域
    }),
  },
  maxCount: {
    type: Number,
    default: 1,
  },
});

import { onMounted } from "vue";
// 选择人员弹窗事件
const iframeSetCookie = () => {
  /*
   * wConfig参数说明

   * selectCategory 选择类型
   *  - 可选择值有 p=公司个人,d=部门,sg=私有群组,vv=私有个人
   *
   * maxCount 最大选择人数
   *
   * sRang 人员范围
   *  - “city” 显示市级 不传或其他就显示全省
   *
   * company 公司名称
   *
   * department 部门名称
   *
   * kWord 关键词
   */
  const jsonData = JSON.stringify({
    selectCategory: props.selectType,
    maxCount: props.maxCount,
  });

  // 设置cookie
  const expireDate = new Date();
  expireDate.setMinutes(expireDate.getMinutes() + 2);
  const domain = props.selectConfig.cookieDomain;
  SetCookie("tmpx110", jsonData, expireDate, "/", domain, false);
};

// 设置cookie
const SetCookie = (name: any, value: any, expires: any, path: any, domain: any, secure: any) => {
  const cookieParts = [] as any[];
  cookieParts.push(name + "=" + escape(value));
  if (expires) {
    cookieParts.push("expires=" + expires.toGMTString());
  }
  if (path) {
    cookieParts.push("path=" + path);
  }
  if (domain) {
    cookieParts.push("domain=" + domain);
  }
  if (secure) {
    cookieParts.push("secure");
  }
  document.cookie = cookieParts.join("; ");
};

// 挂载后执行
onMounted(() => {
  const { postMessageTargetOrigin } = props.selectConfig;

  // 监听 message 事件
  window.addEventListener("message", function (event) {
    if (event.origin == postMessageTargetOrigin) {
      emit("getSelectUserInfo", event.data);
    }
  });

  iframeSetCookie();
});
</script>
